package com.wutongyu.mannyburger;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.textfield.TextInputEditText;

import java.util.ArrayList;
import java.util.List;

public class OrderActivity extends AppCompatActivity {

    private static final String TAG = "OrderActivity";
    private static final String PREF_NAME = "user_prefs";
    private static final String KEY_LOGGED_IN_PHONE = "logged_in_phone";
    
    private RecyclerView productRecyclerView;
    private TextInputEditText noteEditText;
    private TextView totalPriceTextView;
    private Button submitOrderButton;
    private ImageView backButton;
    private RadioGroup deliveryMethodGroup;
    private RadioButton radioPickup;
    private RadioButton radioDelivery;
    private LinearLayout deliveryInfoLayout;
    private TextInputEditText deliveryAddressInput;
    private TextInputEditText deliveryPhoneInput;
    
    private CartManager cartManager;
    private ProductAdapter productAdapter;
    private List<String> productList;
    private Double totalPrice;
    private String userPhone; // 保存当前登录用户手机号
    private UserDatabaseHelper userDbHelper; // 用户数据库帮助类

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        // 获取购物车管理器实例
        cartManager = CartManager.getInstance();
        
        // 获取当前登录用户的手机号
        SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        userPhone = prefs.getString(KEY_LOGGED_IN_PHONE, null); // 如果没有登录，则为null
        
        Log.d(TAG, "当前登录用户: " + (userPhone != null ? userPhone : "未登录"));
        
        // 初始化用户数据库帮助类
        userDbHelper = new UserDatabaseHelper(this);

        // 绑定控件
        bindViews();

        // 设置返回按钮点击事件
        backButton.setOnClickListener(v -> {
            finish(); // 关闭当前Activity，返回上一级
        });

        Intent intent = getIntent();
        String orderDetails = intent.getStringExtra("order_details");
        totalPrice = intent.getDoubleExtra("total_price", 0.0);
        Log.d(TAG, "接收到的总价: " + totalPrice);
        
        // 设置备注信息（如果有）
        String note = intent.getStringExtra("note");
        if (note != null && !note.isEmpty()) {
            noteEditText.setText(note);
        }
        
        // 订单总价格
        totalPriceTextView.setText("合计 ￥" + totalPrice);

        // 产品信息存于List中
        productList = parseOrderDetails(orderDetails);

        // 初始化RecyclerView
        productRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        productAdapter = new ProductAdapter(productList);
        productRecyclerView.setAdapter(productAdapter);
        
        // 设置送餐方式选择监听
        setupDeliveryMethodListener();
        
        // 如果用户已登录，尝试加载地址信息
        if (userPhone != null && !userPhone.isEmpty()) {
            loadUserAddressAndPhone();
        }

        // 监听提交按钮
        submitOrderButton.setOnClickListener(v -> {
            // 检查如果是外卖模式，需要验证地址和电话
            if (radioDelivery.isChecked()) {
                String address = deliveryAddressInput.getText().toString().trim();
                String phone = deliveryPhoneInput.getText().toString().trim();
                
                if (TextUtils.isEmpty(address)) {
                    Toast.makeText(this, "请输入送餐地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入联系电话", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            
            String userNote = noteEditText.getText().toString();
            saveOrderToDatabase(userNote);
            
            // 清空购物车
            cartManager.clearCart();
            cartManager.saveCart(this);
            
            Toast.makeText(OrderActivity.this, "支付成功！总价：￥" + totalPrice, Toast.LENGTH_SHORT).show();
            finish(); // 完成订单后关闭当前Activity
        });
    }
    
    // 绑定视图控件
    private void bindViews() {
        productRecyclerView = findViewById(R.id.productRecyclerView);
        noteEditText = findViewById(R.id.note);
        totalPriceTextView = findViewById(R.id.totalPrice);
        submitOrderButton = findViewById(R.id.submitOrder);
        backButton = findViewById(R.id.backButton);
        
        // 送餐方式相关控件
        deliveryMethodGroup = findViewById(R.id.deliveryMethodGroup);
        radioPickup = findViewById(R.id.radioPickup);
        radioDelivery = findViewById(R.id.radioDelivery);
        deliveryInfoLayout = findViewById(R.id.deliveryInfoLayout);
        deliveryAddressInput = findViewById(R.id.deliveryAddress);
        deliveryPhoneInput = findViewById(R.id.deliveryPhone);
    }
    
    // 设置送餐方式选择监听
    private void setupDeliveryMethodListener() {
        deliveryMethodGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radioDelivery) {
                // 显示送餐地址和电话输入区域
                deliveryInfoLayout.setVisibility(View.VISIBLE);
            } else {
                // 隐藏送餐地址和电话输入区域
                deliveryInfoLayout.setVisibility(View.GONE);
            }
        });
    }
    
    // 加载用户地址和电话信息
    private void loadUserAddressAndPhone() {
        ContentValues userInfo = userDbHelper.getUserInfo(userPhone);
        
        if (userInfo != null) {
            // 设置联系电话（使用登录的手机号）
            deliveryPhoneInput.setText(userPhone);
            
            // 设置地址（如果有）
            String address = userInfo.getAsString(UserDatabaseHelper.COLUMN_ADDRESS);
            if (!TextUtils.isEmpty(address)) {
                deliveryAddressInput.setText(address);
            }
        }
    }

    // 解析订单详情
    private List<String> parseOrderDetails(String orderDetails) {
        List<String> products = new ArrayList<>();
        if (orderDetails != null && !orderDetails.isEmpty()) {
            String[] lines = orderDetails.split("\n");
            for (String line : lines) {
                products.add(line.trim());
            }
        }
        return products;
    }


    // 保存订单到数据库
    private void saveOrderToDatabase(String note) {
        OrderDatabaseHelper dbHelper = new OrderDatabaseHelper(this);
        try {
            StringBuilder itemsStringBuilder = new StringBuilder();
            for (String item : productList) {
                itemsStringBuilder.append(item).append("\n");
            }
            String items = itemsStringBuilder.toString().trim();
            
            // 获取送餐方式
            String deliveryType = radioPickup.isChecked() ? "自提" : "外卖";
            
            // 获取送餐地址和电话
            String deliveryAddress = null;
            String deliveryPhone = null;
            
            if (deliveryType.equals("外卖")) {
                deliveryAddress = deliveryAddressInput.getText().toString().trim();
                deliveryPhone = deliveryPhoneInput.getText().toString().trim();
            }
            
            // 如果用户已登录，则关联用户手机号
            if (userPhone != null && !userPhone.isEmpty()) {
                dbHelper.insertOrder(items, note, totalPrice, userPhone, deliveryType, deliveryAddress, deliveryPhone);
                Log.d(TAG, "订单已保存到数据库，关联用户: " + userPhone);
                
                // 如果是外卖，保存用户地址
                if (deliveryType.equals("外卖") && deliveryAddress != null && !deliveryAddress.isEmpty()) {
                    saveUserAddress(deliveryAddress);
                }
            } else {
                dbHelper.insertOrder(items, note, totalPrice, null, deliveryType, deliveryAddress, deliveryPhone);
                Log.d(TAG, "订单已保存到数据库（匿名订单）");
            }
        } catch (Exception e) {
            Log.e(TAG, "保存订单时出错", e);
            Toast.makeText(this, "保存订单失败", Toast.LENGTH_SHORT).show();
        } finally {
            dbHelper.close(); // 确保关闭数据库连接
        }
    }
    
    // 保存用户地址
    private void saveUserAddress(String address) {
        if (userPhone != null && !userPhone.isEmpty() && address != null && !address.isEmpty()) {
            ContentValues userInfo = userDbHelper.getUserInfo(userPhone);
            
            if (userInfo != null) {
                // 更新用户地址
                userDbHelper.updateUserAddress(userPhone, address);
                Log.d(TAG, "用户地址已更新: " + address);
            }
        }
    }


    // 自定义适配器
    static class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
        private final List<String> productList;

        public ProductAdapter(List<String> productList) {
            this.productList = productList;
        }

        @NonNull
        @Override
        public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
            return new ProductViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
            holder.productNameTextView.setText(productList.get(position));
        }

        @Override
        public int getItemCount() {
            return productList.size();
        }

        static class ProductViewHolder extends RecyclerView.ViewHolder {
            TextView productNameTextView;

            public ProductViewHolder(@NonNull View itemView) {
                super(itemView);
                productNameTextView = itemView.findViewById(android.R.id.text1);
            }
        }
    }
}